from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError


# 审批流模板类
class ProductTemplate(models.Model):
    _inherit = 'product.template'

    active = fields.Boolean('Active', default=False,
                            help="If unchecked, it will allow you to hide the product without removing it.")

    sb_workflow_template_id = fields.Many2one('sb.workflow.template', string="Approval Workflow Template",
                                              domain="[('sb_workflow_template_item_ids', '!=', False), "
                                                     "('workflow_type', 'in', ['other','product'])]")
    sb_workflow_id = fields.Many2one('sb.workflow', string="Current Approval Workflow", copy=False)
    sb_workflow_state = fields.Selection(related="sb_workflow_id.state", readonly=True, string="Approval Status")
    sb_workflow_item_ids = fields.One2many(related="sb_workflow_id.sb_workflow_item_ids", string="Approval Items")
    sb_workflow_attachments_ids = fields.One2many(related="sb_workflow_id.sb_workflow_attachments_ids",
                                                  string="Approval Attachments")
    sb_workflow_ids = fields.One2many('sb.workflow', 'product_id', string="Approval Workflows")
    sb_workflow_ids_sum = fields.Integer(compute="_compute_sb_workflow_ids_sum", store=True)
    # is_approve = fields.Boolean(string="Approve", related="categ_id.is_approve")

    state = fields.Selection([
        ('new', 'New'),
        ('enable', 'Approved')
    ], string="Status", default="new")

    # def create(self, vals):
    #     # 首先调用父类的create方法来创建记录
    #     new_record = super(ProductTemplate, self).create(vals)
    #     if not new_record.is_approve:
    #         # 如果is_approve为False，则设置active字段为True
    #         new_record.write({'active': True})
    #
    #     # 返回创建的记录
    #     return new_record

    # def write(self, vals):
    #     if vals.get('active'):
    #         if self.state != 'enable':
    #             raise ValidationError(
    #                 _('Products that have not been approved cannot be enabled. Please approve first!'))
    #     return super(ProductTemplate, self).write(vals)

    # 生成审批流
    def create_workflow(self):
        if self.sb_workflow_template_id:
            if len(self.sb_workflow_ids) > 0:
                workflow_sum = len(self.sb_workflow_ids) + 1
            else:
                workflow_sum = 1
            # 创建审批流
            new_wf_id = self.env['sb.workflow'].sudo().create({
                'name': self.name + '-Approval Workflow' + '-' + str(workflow_sum),
                'approval_time': fields.Datetime.now(),
                'workflow_type': 'product',
                'product_id': self.id,
            })
            self.sb_workflow_id = new_wf_id.id
            # 根据模板生成审批项
            item_audit_levels = []
            for item in self.sb_workflow_template_id.sb_workflow_template_item_ids:
                new_item = self.env['sb.workflow.item'].sudo().create({
                    'name': item.name,
                    'user_group_ids': item.user_group_ids.ids,
                    'audit_level': item.audit_level,
                    'sb_workflow_id': new_wf_id.id,
                    'state': 'wait_forward'
                })
                # 收集生成的审核项的所有层级
                item_audit_levels.append(new_item.audit_level)
            # 去重排序
            item_audit_levels = list(set(item_audit_levels))
            item_audit_levels.sort()
            # 开放最低层级的神匹配
            for n_item in new_wf_id.sb_workflow_item_ids:
                if n_item.audit_level == item_audit_levels[0]:
                    n_item.state = 'approval'
        else:
            raise ValidationError(_('Please select an approval template'))

    # 跳转审批流页面
    def action_workflow(self):
        return {
            'name': 'Approval Workflows',
            'type': 'ir.actions.act_window',
            'res_model': 'sb.workflow',
            'view_mode': 'form',
            'res_id': self.sb_workflow_id.id,
            # 'views': [(self.env.ref('').id, 'form')],
            'target': 'current',
        }

    # 计算当前单据审批流数
    @api.depends('sb_workflow_ids')
    def _compute_sb_workflow_ids_sum(self):
        for item in self:
            if item.sb_workflow_ids:
                item.sb_workflow_ids_sum = len(item.sb_workflow_ids)
            else:
                item.sb_workflow_ids_sum = 0

    # 跳转当前单据审批流列表
    def action_view_workflow(self):
        return {
            'name': 'Approval Workflows',
            'type': 'ir.actions.act_window',
            'res_model': 'sb.workflow',
            'view_mode': 'tree',
            # 'res_id': self.sb_workflow_id.id,
            # 'views': [(self.env.ref('').id, 'form')],
            'target': 'current',
            'domain': [('product_id', '=', self.id)],
        }
